package com.base.cn.platform.os.controller.mobile.marketing.shortLink;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.service.manage.marketing.shortLink.ShortLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/shortLink")
public class MobileShortLinkController extends MobileBaseController {

    @Autowired
    private ShortLinkService shortLinkService;

    /**
     * 生成短链接
     *
     * @param longUrl 长链接
     *
     * @return Map<String, Object>
     * @author Bingsen.Wang
     */
    @RequestMapping("/getShortLink")
    @ResponseBody
    public Map<String,Object> createShortLink(@RequestParam("longUrl") String longUrl) {
        Map<String, Object> shortLink = shortLinkService.createShortLink(longUrl);
        return shortLink;
    }

    /**
     * 重定向到长链接
     *
     * @param request     HttpServletRequest
     * @param uniqueValue 短链接唯一标识
     * @return String 重定向路径
     * @author Bingsen.Wang
     */
    @RequestMapping("/{uniqueValue}")
    public String redirectLongUrl(HttpServletRequest request,
                                  @PathVariable("uniqueValue") String uniqueValue) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uniqueValue",uniqueValue);
        List<Map<String, Object>> maps = shortLinkService.queryShortLink(map);

        return redirect(request,maps.get(0).get("longLink").toString());
    }

}
